<template>
	<view>
	<u-navbar title="充值礼包" :background="{ backgroundColor: 'rgb(115,114,241)' }" :borderBottom="false"
		titleColor="#fff" backIconColor="#fff"></u-navbar>
		<view>
			<image mode="scaleToFill" style="width: 100%;height: 220rpx;"
				src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/hycz-top1.png"></image>
		</view>
		<view style="width: 97%">
			<image mode="scaleToFill" style="width: 97%;height: 528rpx;position: absolute;"
				src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/hycz-jtym01.png"></image>
			<view style="position: relative;margin-left: 8%;padding-top: 10%;">
				<view>
					<view style="font-size: 34rpx;font-weight: bold;">福利一：充值享钜惠礼包</view>
					<view style="font-size: 10rpx; letter-spacing:-3rpx;">RECHARGE AND ENJOY</view>
				</view>
				<view style="margin-right: 5%;margin-top: 5%;">
					<view class="uni-flex justify-between">
						<view
							style="width: 100%;height: 173rpx;;border-radius: 10rpx;border: 2px solid #F2A356; margin-left: 10rpx;margin-right: 10rpx;"
							v-for="(item,index) in packageList" :key="index">
							<view class="uni-flex uni-column align-center" @click="clickPackageItem(index)"
								v-bind:style="{backgroundColor:bgcolorStyle(item),height:'100%'}">
								<view style="margin-top: 10rpx" class="uni-flex uni-column align-center">
									<view
										style="color: #EB6751;letter-spacing:-3rpx;font-size: 35rpx;font-weight: 600;">
										￥{{(item.packageTopupAmount/100).toFixed(0)}}</view>
									<view style="color: #EB6751;border: 1rpx solid #EB6751;font-size: 24rpx;">
										<view v-if="item.type==0" style="margin-left: 8rpx;margin-right: 8rpx;letter-spacing:-3rpx">
											赠送{{((item.packageGiveAmount)/100).toFixed(0)}}元
										</view>
										<view v-else style="margin-left: 8rpx;margin-right: 8rpx;letter-spacing:-3rpx">
											赠送{{((item.packageGiveAmount-item.packageTopupAmount)/100).toFixed(0)}}元
										</view>
									</view>
									<view style="color: #999999;margin-top: 5rpx;margin-bottom: 15rpx;"
										@click="onDesc(item)" class="uni-flex align-center">
										<view style="font-size: 16rpx;">详情</view>
										<image mode="scaleToFill" style="width: 18rpx;height: 18rpx;"
											src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/hycz-jtym03.png">
										</image>
									</view>
									<view v-if="item.isDesc"
										style="z-index: 0;background-color: rgb(255, 251, 248);border-radius: 14rpx;padding: 0rpx 10rpx 10rpx 10rpx;">
										<view style="font-size: 22rpx;color: #D2873E; "
											v-for="(items,indexs) in item.discountCoupon" :key="indexs">
											{{(items.money/100)}}元抵扣券{{items.num}}张</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="uni-flex justify-center" style="margin-top: 20rpx;">
						<view class="uni-flex justify-center align-center"
							style="width: 50%;height: 70rpx;;background: linear-gradient(0deg, #F2A356 0%, #EB6751 100%);border-radius: 35rpx;">
							<view style="color: white;" @click="submit">{{selectMoney}}确认购买</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="mg-base" style="margin-top: 10%;background-color: white;border-radius: 14rpx;">
			<u-read-more open-text="收起" close-text="购买须知" color="#333333" :shadow-style="shadowStyle" :toggle="true"
				show-height="0">
				<view class="uni-flex justify-center" style="margin-top: 20rpx;">
					<view style="font-size: 26rpx;font-weight: 600;">购买须知：</view>
				</view>
				<view class="mg-sm">
					<rich-text :nodes="desc" @load="parseLoaded"></rich-text>
				</view>
			</u-read-more>
		</view>
		<view style="margin-top: 5%;margin-left: 40rpx;margin-right: 40rpx;">
			<view>
				<view>
					<image mode="scaleToFill" style="height: 150rpx;width: 89%;;position: absolute;"
						src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/hycz-jtym02 (1).png">
					</image>
				</view>
				<view style="position: relative;padding-left: 6%;padding-top: 5%;">
					<view class="uni-flex uni-column justify-start">
						<view><text style="font-size: 34rpx;font-weight: bold;">福利二：分享商品赚佣金</text></view>
						<view><text style="font-size: 20rpx;letter-spacing:-3rpx;">SHARING GOODS</text></view>
					</view>
				</view>
			</view>
		</view>
		<view style="margin-left: 40rpx;margin-right: 40rpx;width: 89%">
			<view style="width: 100%;background-color: white;">
				<view v-if="list.length" class="l-pad r-pad">
					<uni-grid :column="2" :square="false" :showBorder="false" @change="handleGoodsChange">
						<uni-grid-item v-for="(item, index) in list" :key="item.id" :index="index">
							<view class="uni-flex uni-column b-mg" :class="{'align-end': (index + 1) % 2 === 0}">
								<view class="goods-info pos-real">
									<view class="h-fill">
										<u-lazy-load loading-img="/static/easy-loadimage/loading.gif"
											error-img="/static/img/img_home_quesheng@2x.png"
											:borderRadius="[20, 20, 0, 0]" :image="item.thumb" :height="345"
											img-mode="aspectFill"></u-lazy-load>
										<view class="goods-info-sale">已售{{item.sellInfo.totalSellCount || "0"}}</view>
										<view v-if="item.is_time_limited"
											class="pos-abs-lt pos-abs-rt countdown justify-center h-box"
											:class="{'countdown-short': item.sellInfo.maxShareReward && userInfo.shareGrade}">
											<u-count-down :showBoard="false" :font-size="22" :separator-size="22"
												bgColor="" separator="zh-day" fontSize="20" separatorColor="#fff"
												color="#fff" :timestamp="getSeconds(item.sale_deadline)"></u-count-down>
											<view class="countdown-label" style="margin-left: 8rpx;">结束</view>
										</view>
										<view v-if="!item.sellInfo.totalStock"
											class="goods-info-stock-over uni-flex align-center justify-center"
											style="color: #fff;">
											<text>已售罄</text>
										</view>
									</view>
									<view v-if="item.sellInfo.maxShareReward && userInfo.shareGrade"
										class="pos-abs view-max-brokrage">
										<view class="pos-abs view-max-brokrage-bg-red"></view>
										<view class="pos-abs view-max-brokrage-bg-white"></view>
										<text
											class="pos-abs text-white view-max-brokrage-money">￥{{item.sellInfo.maxShareReward / 100}}</text>
										<text class="pos-abs text-red view-max-brokrage-tip">最高赚>></text>
									</view>
									<view v-else-if="item.sellInfo.maxShareReward>0 && (!userInfo.id||userInfo.shareGrade==0)"
										class="pos-abs view-max-brokrage">
										<view class="pos-abs view-max-brokrage-bg-red"></view>
										<view class="pos-abs view-max-brokrage-bg-white"></view>
										<text
											class="pos-abs text-white view-max-brokrage-money">￥{{item.sellInfo.maxShareReward / 100}}</text>
										<text class="pos-abs text-red view-max-brokrage-tip">最高赚>></text>
									</view>
									<view class="pad goods-info-detail pos-real">
										<view class="goods-info-name-2 uni-bold">{{item.name || ''}}</view>
										<view class="t-mg uni-flex align-center">
											<text class="uni-bold"
												style="color: #D61719;">￥{{item.sellInfo.price / 100 || '0'}}</text>
											<text
												class="uni-flex-extend uni-text-gray uni-text-del">￥{{item.sellInfo.market_price / 100 || '0'}}</text>
											<text v-if="item.distance !== undefined"
												class="uni-text-gray uni-text-small">距您{{formatDistance(item.distance)}}</text>
										</view>
									</view>
								</view>
							</view>
						</uni-grid-item>
					</uni-grid>
					<uni-load-more :status="loadingStatus"></uni-load-more>
				</view>
			</view>
		</view>

		<view>
			<u-toast ref="uToast" />
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations,
		mapActions
	} from 'vuex';
	import {
		getUserInfo,
		getUserPackageSearch,
		getPackageProperty,
		getHomeData
	} from "@/api/platform/user.js";
	import util from "@/common/util.js";
	import {
		genPackageOrder,
		genPayInfo,
		updatePakcageState
	} from "@/api/platform/order.js";
	const db = uniCloud.database()
	
	function getParam(query, name){
		query = query.substring(query.indexOf('?') + 1)
		let reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`)
		let result = query.match(reg)
		if(result == null){
			return null
		}else{
			return result[2]
		}
	}
	export default {
		data() {
			return {
				storeId: '',
				list: [],
				homeData: [],
				packageList: [],
				onPackageId: '',
				shadowStyle: {
					backgroundImage: "none",
					paddingTop: "0",
					marginTop: "20rpx"
				},
				desc: "",
				selectMoney: ''
			}
		},
		computed: {
			...mapState(["userInfo"])
		},
		async onLoad(e) {
			if (e.q) {
				let query = decodeURIComponent(e.q)
				this.storeId = getParam(query, 'storeId')
				this.shareManId = getParam(query, 'shareManId')
				// let matches = /storeId=\S+@/.exec(params)
				// if (matches) {
				// 	this.storeId = matches[0].split('=')[1].replace('@', '')
				// }
				// if (!this.storeId) {
				// 	matches = /storeId=\S+/.exec(params)
				// 	if (matches) {
				// 		this.storeId = matches[0].split('=')[1]
				// 	}
				// }
				// matches = /shareManId=\S+@/.exec(params)
				// if (matches) {
				// 	this.shareManId = matches[0].split('=')[1].replace('@', '')
				// }
			} else {
				this.storeId = e.storeId
				this.shareManId = e.shareManId
			}
			console.log('storeId', this.storeId, 'shareManId', this.shareManId)
			if (!this.storeId) {
				uni.showModal({
					title: '提示',
					content: '充值未配置正确，请联系客服！',
					showCancel: false,
					success: (res) => {
						if (res.confirm) {
							uni.switchTab({
								url: '/pages/user/user'
							})
						}
					}
				})
			}
		},
		async onReady() {
			if (!this.storeId) {
				return
			}
			uni.showLoading({
				mask: true
			})
			await this.getData()
			uni.hideLoading()
		},
		async onPullDownRefresh() {
			await this.getData();
			uni.stopPullDownRefresh();
		},
		methods: {
			...mapMutations(['updateUserInfo']),
			...mapActions(['setShareManId', 'getCurrRegion']),
			formatDistance: util.formatDistance,
			async reload() {
				if (this.loadingStatus === "loading") {
					return;
				}
				this.list = [];
				this.pageNum = 1;
				this.loadingStatus = "more";
				uni.showLoading({
					mask: true
				})
				try {
					let data = await this.getCurrRegion()
					console.log('currRegion', data)
					this.homeData = await getHomeData({
						showLoading: false,
						city: data.currRegion.city.value,
						userLocation: data.userLocation
					})
					this.list = this.sortGoods(this.homeData.goods.list)
					uni.hideLoading()
				} catch (e) {
					console.error(e)
					uni.hideLoading()
				}
			},
			async getPackageList() {
				const dbCmd = db.command
				let adInfo = await db.collection('t3ds-store-ad').where(`storeId == '${this.storeId}'`).get();
				//let adInfo = await db.collection('t3ds-store-ad').where(`storeId == '859059a5618a2cd4049aef0c2ed51d4e'`).get();
				if (!adInfo.result.data.length) {
					this.$refs.uToast.show({
						title: "当前门店没有配置静态礼包"
					})
					return
				}
				this.desc = adInfo.result.data[0].dbDesc
				console.log("adInfo", adInfo)
				// let packageList = await db.collection('t3ds-package').where({
				// 	_id: dbCmd.in(adInfo.result.data[0].packageId)
				// }).get();
				// console.log("packageList",packageList)
				// let packageList = await db.collection('t3ds-package').where(
				// 	`storeId == '${this.storeId}' && isStaticPackage == 1 `).get();
				var data = [];
				var packageIds = adInfo.result.data[0].packageId;
				for (var i = 0; i < packageIds.length; i++) {
					let packageInfo = await db.collection('t3ds-package').where({
						_id: packageIds[i]
					}).get();
					data.push(packageInfo.result.data[0])
				}
				//var data = packageList.result.data;
				for (var i = 0; i < data.length; i++) {
					data[i].isClick = false;
					data[i].isDesc = false;
				}
				this.packageList = data
				console.log(this.packageList)
			},
			async packagePay(packageId) {
				//console.log("packagePay", this.userInfo)
				try {
					uni.showLoading({
						mask: true,
						title: '检测支付环境'
					})
					var orderPayInfo;
					const order = await genPackageOrder({
						packageId: packageId,
						shareManId: this.shareManId,
						showLoading: false
					});
					orderPayInfo = await genPayInfo({
						orderId: order._id,
						showLoading: false
					});
					console.log("234", orderPayInfo)

					// await updatePakcageState({
					// 	orderId: packageId,
					// 	user: this.userInfo,
					// 	showLoading: false
					// });


					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: orderPayInfo.timeStamp,
						nonceStr: orderPayInfo.nonceStr,
						package: orderPayInfo.package,
						signType: orderPayInfo.signType,
						paySign: orderPayInfo.paySign,
						success: async (res) => {
							console.log('支付成功', res)
							uni.navigateTo({
								url: "./topup"
							})
							//let success = await this.finishPay(order)
							//await this.getDisCountInfo()
							uni.hideLoading()
							this.getData()
						},
						fail: (err) => {
							console.log('用户取消支付', err)
							uni.hideLoading()
						}
					})
				} catch (e) {
					console.log(e)
					uni.hideLoading()
					//TODO handle the exception
				}

			},
			sortGoods(list) {
				let sellOut = []
				for (var i = 0; i < list.length; i++) {
					let item = list[i]
					if (!item.sellInfo.totalStock) {
						sellOut.push(item)
						list.splice(i, 1)
						i--
					}
				}
				return list.concat(sellOut)
			},
			getStoreList(storeIdx) {
				console.log("storeIdx", storeIdx)
				const dbCmd = db.command
				const $ = dbCmd.aggregate
				db.collection('t3ds-store').where({
					_id: dbCmd.in(storeIdx)
				}).field("name").get().then(res => {
					this.storeListPopup = res.result.data;
					this.storeListShow = true
					//console.log("storeList",res)
				})
				// console.log(storeIdx)
			},
			async getData() {
				await this.getPackageList()
				await this.getGoods()
				//this.loadDisCount()
				//await this.reload()
			},
			async getGoods() {
				let data = await this.getCurrRegion()
				console.log('currRegion', data)
				this.homeData = await getHomeData({
					showLoading: false,
					city: data.currRegion.city.value,
					userLocation: data.userLocation
				})
				var goods = this.sortGoods(this.homeData.goods.list)
				//2024.2.5 丁斌暂定修改只显示两条
				this.list[0] = goods[0]
				this.list[1] = goods[1]
				console.log("getGoods", this.list)
			},
			bgcolorStyle(item) {
				return item.isClick ? '#FFEEDE' : ''
			},
			clickPackageItem(index) {
				this.packageList[index].isClick = !this.packageList[index].isClick
				for (var i = 0; i < this.packageList.length; i++) {
					if (i != index) {
						this.packageList[i].isClick = false
					}
				}
				if (this.packageList[index].isClick) {
					this.onPackageId = this.packageList[index]._id
					this.selectMoney = (this.packageList[index].packageTopupAmount / 100) + "元 "
				} else {
					this.onPackageId = ''
				}

			},
			submit() {
				if (this.onPackageId) {
					this.packagePay(this.onPackageId)
				} else {
					this.$refs.uToast.show({
						title: "请选择礼包"
					})
				}

			},
			onDesc(item) {
				item.isDesc = !item.isDesc
				console.log(item.isDesc)
			},
			onDisCountItemDesc(item) {
				this.$refs.uToast.show({
					title: item.desc,
					type: 'primary'
				})
			},
			storeListShowclose() {},
			parseLoaded() {
				this.$refs.uReadMore.init();
			},
			handleGoodsChange(e) {
				uni.navigateTo({
					url: "/pagesGroup/platform/goods-detail?goodsId=" + this.list[e.detail.index]._id
				})
			},
		}
	}
</script>

<style>
	page {
		background-color: #F5F5F5;
	}
</style>

<style lang="scss" scoped>
	.u-tabs {
		background: #EBEBEB !important;
		height: 100rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		padding: 0 30rpx;
		border-radius: 50rpx;
	}

	.content {
		margin-top: 560rpx;
		padding-bottom: 60rpx;

		.content-money {
			height: 100%;
			position: relative;
			z-index: 9;
		}

		.content-item-1 {
			width: 690rpx;
			height: 170rpx;
			margin: 0 30rpx;
		}

		.content-item-2 {
			width: 330rpx;
			height: 130rpx;
		}

		.content-operate {
			background: #FFFFFF;
			border-radius: 24rpx;
			margin: 60rpx 30rpx 0 30rpx;
			padding: 0 30rpx;

			.content-operate-item:not(:last-child) {
				border-bottom: 1px solid #EAEAEA;
				;
			}
		}

		.content-btn {
			margin: 88rpx 30rpx 0 30rpx;

			.content-btn-0 {
				width: 330rpx;
				height: 88rpx;
				border-radius: 50rpx;
				font-size: 30rpx;
				color: white;
			}

			.content-btn-1 {
				background-color: #CFCFCF;
			}

			.content-btn-2 {
				background: #FF5673;
			}
		}

		.content-explain {
			margin: 60rpx 30rpx 0 30rpx;
			background: #E9E9E9;
			border-radius: 24rpx;
			padding: 30rpx;

			.content-explain-icon {
				width: 32rpx;
				height: 32rpx;
				filter: grayscale(1);
			}

			.content-explain-title {
				font-size: 30rpx;
				color: #5A5A5C;
			}
		}
	}


	.searchBgc {
		background-image: linear-gradient(to right, #434AD8, #8E77F5);
		padding: 21rpx 40rpx;

		.search {
			background: #8586E6;
			color: white;
			border-radius: 32rpx;
			padding: 13rpx 30rpx;

			display: flex;
			align-items: center;

			.left {
				// width: 110rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding-right: 20rpx;
				font-size: 30rpx;

				.textLeft {
					max-width: 150rpx;
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
				}

				image {
					width: 18rpx;
					height: 12rpx;
					margin-left: 5rpx;
				}
			}

			.right {
				flex: 1;
				color: #A7A7EB;
				border-left: 1px solid #C0C0E9;
				padding-left: 20rpx;
				font-size: 28rpx;

				display: flex;
				justify-content: space-between;
			}
		}
	}

	.goods-info {
		// width: 345rpx;
		margin-left: 5rpx;
		margin-right: 5rpx;
		border: 1rpx solid rgb(245, 245, 245);
		border-top-right-radius: 20rpx;
		border-top-left-radius: 20rpx;
		position: relative;

		&-sale {
			position: absolute;
			top: 0;
			right: 0;
			border-top-right-radius: 20rpx;
			border-bottom-left-radius: 20rpx;
			background-color: rgba($color: #000000, $alpha: 0.3);
			height: 48rpx;
			line-height: 48rpx;
			padding: 0 20rpx;
			color: rgba($color: #fff, $alpha: 0.9);
			font-size: 22rpx;
		}

		&-detail {
			background-color: #FFFFFF;
			border-bottom-left-radius: 20rpx;
			border-bottom-right-radius: 20rpx;
			z-index: 99;
		}

		&-stock-over {
			position: absolute;
			top: 0;
			right: 0;
			left: 0;
			height: 345rpx;
			background-color: rgba($color: #000000, $alpha: 0.2);
		}

		.countdown {
			background-color: rgba($color: #000000, $alpha: 0.3);
			height: 60rpx;
			top: 285rpx;
			padding: 0 20rpx;
			color: #FFFFFF;

			&-label {
				font-size: 20rpx;
			}
		}

		.countdown-short {
			justify-content: flex-end;
			-webkit-clip-path: polygon(76rpx 0, 100% 0, 100% 100%, 76rpx 60rpx, 85rpx 45rpx, 90rpx 30rpx, 85rpx 15rpx);
		}

		/deep/ .u-countdown {
			height: 60rpx !important;
		}
	}

	.img-category {
		width: 120rpx;
		height: 120rpx;
	}

	.category-item {
		display: inline-block;
	}

	.category-item:not(:last-child) {
		margin-right: 63rpx;
	}

	.scroll-h {
		white-space: nowrap;
	}

	.page-top {
		background-color: #FFFFFF;
	}

	.page-bot {
		position: relative;
		background-color: #F5F5F5;
		top: -20rpx;
		border-top-left-radius: 40rpx;
		border-top-right-radius: 40rpx;
		padding-top: 20rpx;
	}

	.btn-search {
		width: 60rpx;
		height: 60rpx;
	}

	.view-max-brokrage {
		width: 110rpx;
		height: 110rpx;
		left: -20rpx;
		top: calc(345rpx - 80rpx);

		&-bg-red {
			background-color: rgba($color: #f00, $alpha: 0.7);
			width: 100%;
			height: 50%;
			border-top-left-radius: 150rpx;
			border-top-right-radius: 150rpx;
			clip: rect(0rpx, 140rpx, 76rpx, 20rpx);
		}

		&-bg-white {
			background-color: #FFFFFF;
			width: 100%;
			height: 50%;
			top: 50%;
			border-bottom-right-radius: 150rpx;
			clip: rect(0rpx, 140rpx, 76rpx, 20rpx);
		}

		&-money {
			font-size: 26rpx;
			top: calc(50% - 36rpx);
			width: 100%;
			text-align: center;
			line-height: 1;
		}

		&-tip {
			font-size: 18rpx;
			top: calc(50% + 5rpx);
			width: 100%;
			line-height: 1;
			text-align: right;
			padding-right: 10rpx;
		}
	}
</style>